<template>
  <div class="container">
    <div class="app-container">
      <el-tree :expand-on-click-node="false" default-expand-all :data="depts" :props="defaultProps">
        <template v-slot="{data}">
          <el-row type="flex" style="width: 100%">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span style="margin-right: 10px" class="tree-manager">管理员</span>
              <el-dropdown @command="handleCommand($event,data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <drop-dialog ref="dropRef" :currentnodeid="currentNodeId" :showdialog.sync="show" @updateDepartment="getDepartment" />
  </div>
</template>
<script>
import { getDepartment, delDepartment } from '@/api/department'
import { transListToTreeDate } from '@/utils/index'
import dropDialog from './components/drop-dialog.vue'
export default {
  name: 'Department',
  components: { dropDialog },
  data() {
    return {
      show: false,
      currentNodeId: null,
      depts: [{
        name: '传智教育',
        children: [
          { name: '总裁办' },
          { name: '行政部' },
          { name: '财务部' }
        ]
      }],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      const res = await getDepartment()
      this.depts = transListToTreeDate(res, 0)
    },
    async  handleCommand(type, id) {
      this.currentNodeId = id
      if (type === 'add') {
        console.log('点击了添加')
        this.show = true
      } else if (type === 'edit') {
        console.log('点击了编辑')
        this.show = true
        this.$nextTick(() => {
          this.$refs.dropRef.getDepartmentDetail()
        })
      } else {
        await this.$confirm('您确认要删除该部门吗')
        await delDepartment(id)
        this.$message.success('删除部门成功')
        this.getDepartment()
      }
    }
  }
}
</script>

<style scoped>
/* .app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  width: 50px;
  display: inline-block;
  margin: 10px;
} */
</style>
